package com.fancon.android.gardenjokesx.dialog;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.fancon.android.core.IFanconGlobalState;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.P01FromS06;
import com.fancon.android.gardenjokesx.activity.S03_1Activity;
import com.fancon.android.gardenjokesx.activity.S03_2Activity;
import com.fancon.android.gardenjokesx.activity.SignupActivity;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.TwitterUser;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.DownloadImageTask;
import com.fancon.android.gardenjokesx.utils.DownloadImageTask.IExcuteUi;
import com.fancon.android.gardenjokesx.utils.UserUtil;

public class ProfilePictureSettingDialog extends Dialog {

	private static final int PICK_FROM_CAMERA = 1;
	//private static final int CROP_FROM_CAMERA = 2;
	private static final int PICK_FROM_FILE = 3;
	private Bundle b;
	private Context mContext;
	private User mUser;
	private DatabaseHelper db;
	private boolean isFacebookLinked = false;
	private boolean isTwitterLinked = false;

	public ProfilePictureSettingDialog(Context context, Bundle bundle) {
		super(context, android.R.style.Theme_Translucent_NoTitleBar);
		// TODO Auto-generated constructor stub
		setContentView(R.layout.mesx_edit_profile_picture_s06);
		mContext = context;
		this.b = bundle;
		db = new DatabaseHelper(mContext);
		View cancel = findViewById(R.id.s06_btnCance);
		if (b.getInt(Constant.SCREEN_ID) == Constant.S01
				|| b.getInt(Constant.SCREEN_ID) == Constant.U02) {
			b.putInt(Constant.PRE_SCREEN_ID, b.getInt(Constant.SCREEN_ID));
		}
		b.putInt(Constant.SCREEN_ID, Constant.S06);
		cancel.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dismiss();
			}
		});
		// Remove picture BTN
		Button mBtnRemovePicture = (Button) findViewById(R.id.s06_btnRemovePicture);
		mBtnRemovePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.S01) {
					mUser.setUrl_image("drawable");
					b.putSerializable("user", mUser);
					Intent intent = new Intent(getContext(),
							SignupActivity.class);
					intent.putExtras(b);
					getContext().startActivity(intent);
				}
				if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.U02) {
					Bitmap bm = BitmapFactory.decodeResource(
							mContext.getResources(),
							R.drawable.common_default_avatar);

					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					bm.compress(CompressFormat.JPEG, 100, bos);
					byte[] data = bos.toByteArray();
					ByteArrayBody bad = new ByteArrayBody(data, "avatar.jpg");
					MultipartEntity reqEntity = new MultipartEntity();
					String user_id = UserUtil.getInfoUserLogin(mContext)
							.getUser_id();
					try {
						reqEntity.addPart("image", bad);
						reqEntity.addPart("user_id", new StringBody(user_id));
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// @binhbt-comment
					// Need use multithread for enhance performent
					GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
							mContext);
					String result = apiConnect.execPostImg(mContext,
							GardenJokesApiConnect.GROUP_S,
							"updateImageProfile", reqEntity);
					Log.d("S06", "post result: " + result);
				}
				dismiss();
			}
		});
		// If image url is'nt set, mBtnRemovePicture is invisible.
		if (b != null && b.getInt(Constant.PRE_SCREEN_ID) == Constant.S01) {
			mUser = (User) b.getSerializable("user");
			if (mUser.getUrl_image().equalsIgnoreCase("drawable")) {
				mBtnRemovePicture.setVisibility(View.GONE);
			}
		}
		if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.U02) {
			// Create database, check facebook, twitter linked.
			try {
				String user_id = UserUtil.getInfoUserLogin(mContext).getUser_id();
				isFacebookLinked = db.isFacebookLinked(user_id);
				isTwitterLinked = db.isTwitterLinked(user_id);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
		// choose picture
		Button mBtnChoosePicture = (Button) findViewById(R.id.s06_btnChoosePicture);
		mBtnChoosePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				b.putInt("type", PICK_FROM_FILE);
				Intent intent = new Intent(getContext(), P01FromS06.class);
				intent.putExtras(b);
				getContext().startActivity(intent);
				dismiss();
				if (mContext instanceof SignupActivity) {
					((SignupActivity) mContext).finishSignUpActivity();
				}
			}
		});
		// take picture
		Button mBtnTakePicture = (Button) findViewById(R.id.s06_btnTakePicture);
		mBtnTakePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("S06", "screen id: " + b.getInt(Constant.SCREEN_ID));
				Intent intent = new Intent(getContext(), P01FromS06.class);
				b.putInt("type", PICK_FROM_CAMERA);
				intent.putExtras(b);
				getContext().startActivity(intent);
				dismiss();
				if (mContext instanceof SignupActivity) {
					((SignupActivity) mContext).finishSignUpActivity();
				}
			}
		});
		PackageManager pm = context.getPackageManager();

		if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false) {
			mBtnTakePicture.setVisibility(View.GONE);
		}

		// import facebook
		Button mBtnImportFacebook = (Button) findViewById(R.id.s06_btnImportFromFacebook);
		mBtnImportFacebook.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String token = "";
				Log.d("S06", "pre screen: " + b.getInt(Constant.PRE_SCREEN_ID));
				if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.S01
						&& b.getString(Constant.FACEBOOK_ACCESS_TOKEN) != null) {
					((SignupActivity) mContext).getFacebookUser();
					// If facebook has connected
				} else if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.U02
						&& isFacebookLinked == true) {
					final String user_id = UserUtil.getInfoUserLogin(mContext)
							.getUser_id();
					FacebookUser currentFacebookUser = db
							.getFacebookUser(user_id);
					b.putString(Constant.FACEBOOK_ACCESS_TOKEN,
							currentFacebookUser.getAccessToken());
					Log.d("S06",
							"Facebook access token:  "
									+ b.getString(Constant.FACEBOOK_ACCESS_TOKEN));

					token = b.getString(Constant.FACEBOOK_ACCESS_TOKEN);

					SocialUntil social = new SocialUntil(mContext);
					User fbUser = social.userInfoFB(token);

					// ImageLoader imageLoader =
					// ((IMeshCache)mActivity).getmImgLoader();
					// String imageProfileUrl =
					// imageLoader.getImageFromSD(fbUser.getUrl_image());
					// Log.d("S06","profile url:  "+imageProfileUrl);
					// @binhbt added
					IExcuteUi ie = new IExcuteUi() {

						@Override
						public void preExecute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void execute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void executeUI(String realPath) {
							// TODO Auto-generated method stub
							// Log.d("S06","profile url:  "+imageProfileUrl);
							Bitmap bm = BitmapFactory.decodeFile(realPath);
							ByteArrayOutputStream bos = new ByteArrayOutputStream();
							bm.compress(CompressFormat.JPEG, 100, bos);
							byte[] data = bos.toByteArray();
							ByteArrayBody bad = new ByteArrayBody(data,
									"avatar.jpg");
							MultipartEntity reqEntity = new MultipartEntity();
							try {
								reqEntity.addPart("image", bad);
								reqEntity.addPart("user_id", new StringBody(
										user_id));
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
							// @binhbt-comment
							// Need multi thread
							GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
									mContext);
							String result = apiConnect.execPostImg(mContext,
									GardenJokesApiConnect.GROUP_S,
									"updateImageProfile", reqEntity);
							Log.d("S06", "post result: " + result);
						}

					};

					DownloadImageTask photoReq = new DownloadImageTask(
							"photo_rq", (Activity) mContext, fbUser
									.getUrl_image());
					photoReq.setIe(ie);
					((IFanconGlobalState) mContext).getRequestQueue()
							.addRequest(photoReq);
					//
				} else {
					Intent intent = new Intent(getContext(),
							S03_2Activity.class);
					intent.putExtras(b);
					getContext().startActivity(intent);
				}
				dismiss();
			}
		});

		Button mBtnImportTwitter = (Button) findViewById(R.id.s06_btnImportFromTwitter);
		mBtnImportTwitter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String token = "", secret = "";
				Log.d("S06", "pre screen: " + b.getInt(Constant.PRE_SCREEN_ID));
				if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.S01
						&& b.getString(Constant.TWITTER_ACCESS_TOKEN) != null) {
					Log.d("S06",
							"Twitter access token:  "
									+ b.getString(Constant.TWITTER_ACCESS_TOKEN));
					((SignupActivity) mContext).getTwitterUser();
					// If twitter has connected
				} else if (b.getInt(Constant.PRE_SCREEN_ID) == Constant.U02
						&& isTwitterLinked == true) {

					final String user_id = UserUtil.getInfoUserLogin(mContext)
							.getUser_id();
					TwitterUser twiUser = db.getTwitterUser(user_id);
					b.putString(Constant.TWITTER_ACCESS_TOKEN,
							twiUser.getTwitterToken());
					b.putString(Constant.ACCESS_SECRET,
							twiUser.getTwitterSecret());

					token = b.getString(Constant.TWITTER_ACCESS_TOKEN);
					secret = b.getString(Constant.ACCESS_SECRET);

					SocialUntil social = new SocialUntil(mContext);
					// Get url image profile user
					String url = social.getImageProfile(token, secret);

					// @binhbt-added
					IExcuteUi ie = new IExcuteUi() {

						@Override
						public void preExecute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void execute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void executeUI(String realPath) {
							// TODO Auto-generated method stub
							Log.d("S06", "profile url:  " + realPath);
							Bitmap bm = BitmapFactory.decodeFile(realPath);
							ByteArrayOutputStream bos = new ByteArrayOutputStream();
							bm.compress(CompressFormat.JPEG, 100, bos);
							byte[] data = bos.toByteArray();
							ByteArrayBody bad = new ByteArrayBody(data,
									"avatar.jpg");
							MultipartEntity reqEntity = new MultipartEntity();

							try {
								reqEntity.addPart("image", bad);
								reqEntity.addPart("user_id", new StringBody(
										user_id));
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
							// @binhbt-comment
							// Need multireq for enhance performent
							GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
									mContext);
							String result = apiConnect.execPostImg(mContext,
									GardenJokesApiConnect.GROUP_S,
									"updateImageProfile", reqEntity);
							Log.d("S06", "post result: " + result);
						}

					};

					DownloadImageTask photoReq = new DownloadImageTask(
							"photo_rq", (Activity) mContext, url);
					photoReq.setIe(ie);
					((IFanconGlobalState) mContext).getRequestQueue()
							.addRequest(photoReq);
					//

				} else {
					Intent intent = new Intent(getContext(),
							S03_1Activity.class);
					intent.putExtras(b);
					getContext().startActivity(intent);
				}
				dismiss();
			}
		});
	}
}